package com.dson.monitor;


import com.google.common.collect.Maps;

import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

public class Monitor implements Runnable {

    // 存储请求时间和请求耗时
    public Map<String, Map<Long,Long>> costTimeMaps = new ConcurrentHashMap<>(2000);

    // 请求过期数据
    private void clearOld(){
        long valid = System.currentTimeMillis()-1000*60;
        Iterator<String> iterator = costTimeMaps.keySet().iterator();
        while (iterator.hasNext()){
            String method = iterator.next();
            Map<Long, Long> costMap = costTimeMaps.get(method);
            Iterator<Map.Entry<Long, Long>> iterator1 = costMap.entrySet().iterator();
            while (iterator1.hasNext()){
                Long time = iterator1.next().getKey();
                if(time<valid){
                    iterator1.remove();
                }
            }
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(5000);

                synchronized (Monitor.class) {
                    final Map<String, Map<Long, Long>> temp = new HashMap<>();
                    temp.putAll(costTimeMaps);
                    int total = temp.size();
                    if (total == 0) {
                        continue;
                    }
//                    clearOld();

                    for (String method : temp.keySet()) {
                        Object[] sortedCosts = temp.get(method).values().toArray();
                        Arrays.sort( sortedCosts);
                        int tp90 = (int) (sortedCosts.length * 0.9);
                        int tp99 = (int) (sortedCosts.length * 0.99);
                        System.out.println(method + " tp90,cost:" + sortedCosts[tp90] + "ms");
                        System.out.println(method + " tp99,cost:" + sortedCosts[tp99] + "ms");
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
